<template>
    <div class="main p-center">
        <a-form id="formLogin" class="user-layout-login" ref="formLogin" :form="form" @submit="handleSubmit">
            <h1>四川省安全发展示范城市信息化管理系统</h1>
            <a-tabs
                :activeKey="customActiveKey"
                :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
                @change="handleTabClick"
            >
                <a-tab-pane key="account" :tab="$t('user.login.tab-login-credentials')">
                    <a-alert
                        v-if="isLoginError"
                        type="error"
                        showIcon
                        style="margin-bottom: 24px"
                        :message="$t('user.login.message-invalid-credentials')"
                    />
                    <a-form-item>
                        <a-input
                            size="large"
                            type="text"
                            :placeholder="$t('user.login.username.placeholder')"
                            v-decorator="[
                                'username',
                                {
                                    initialValue: username,
                                    rules: [
                                        { required: true, message: $t('user.username.required') },
                                        { validator: handleusernameOrEmail },
                                    ],
                                    validateTrigger: 'change',
                                },
                            ]"
                        >
                            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input>
                    </a-form-item>

                    <a-form-item>
                        <a-input-password
                            size="large"
                            :placeholder="$t('user.login.password.placeholder')"
                            v-decorator="[
                                'password',
                                {
                                    initialValue: password,
                                    rules: [{ required: true, message: $t('user.password.required') }],
                                    validateTrigger: 'blur',
                                },
                            ]"
                        >
                            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
                        </a-input-password>
                    </a-form-item>
                </a-tab-pane>
                <!--                <a-tab-pane key="mobile" :tab="$t('user.login.tab-login-mobile')">-->
                <!--                    <a-form-item>-->
                <!--                        <a-input-->
                <!--                            size="large"-->
                <!--                            type="text"-->
                <!--                            :placeholder="$t('user.login.mobile.placeholder')"-->
                <!--                            v-decorator="[-->
                <!--                                'mobile',-->
                <!--                                {-->
                <!--                                    rules: [-->
                <!--                                        {-->
                <!--                                            required: true,-->
                <!--                                            pattern: /^1[34578]\d{9}$/,-->
                <!--                                            message: $t('user.login.mobile.placeholder'),-->
                <!--                                        },-->
                <!--                                    ],-->
                <!--                                    initialValue: mobile,-->
                <!--                                    validateTrigger: 'change',-->
                <!--                                },-->
                <!--                            ]"-->
                <!--                        >-->
                <!--                            <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }" />-->
                <!--                        </a-input>-->
                <!--                    </a-form-item>-->

                <!--                    <a-row :gutter="16">-->
                <!--                        <a-col class="gutter-row" :span="16">-->
                <!--                            <a-form-item>-->
                <!--                                <a-input-->
                <!--                                    size="large"-->
                <!--                                    type="text"-->
                <!--                                    :placeholder="$t('user.login.mobile.verification-code.placeholder')"-->
                <!--                                    v-decorator="[-->
                <!--                                        'captcha',-->
                <!--                                        {-->
                <!--                                            rules: [{ required: true, message: $t('user.verification-code.required') }],-->
                <!--                                            validateTrigger: 'blur',-->
                <!--                                        },-->
                <!--                                    ]"-->
                <!--                                >-->
                <!--                                    <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />-->
                <!--                                </a-input>-->
                <!--                            </a-form-item>-->
                <!--                        </a-col>-->
                <!--                        <a-col class="gutter-row" :span="8">-->
                <!--                            <a-button-->
                <!--                                class="getCaptcha"-->
                <!--                                tabindex="-1"-->
                <!--                                :disabled="state.smsSendBtn"-->
                <!--                                @click.stop.prevent="getCaptcha"-->
                <!--                                v-text="-->
                <!--                                    (!state.smsSendBtn && $t('user.register.get-verification-code')) ||-->
                <!--                                    state.time + ' s'-->
                <!--                                "-->
                <!--                            ></a-button>-->
                <!--                        </a-col>-->
                <!--                    </a-row>-->
                <!--                </a-tab-pane>-->
            </a-tabs>

            <a-form-item>
                <a-checkbox v-decorator="['rememberMe', { initialValue: rememberMe, valuePropName: 'checked' }]">
                    {{ customActiveKey === 'account' ? $t('user.login.remember-me') : '记住手机号' }}
                </a-checkbox>
            </a-form-item>

            <a-form-item style="margin-top: 24px">
                <a-button
                    size="large"
                    type="primary"
                    htmlType="submit"
                    class="login-button"
                    :loading="state.loginBtn"
                    :disabled="state.loginBtn"
                >
                    {{ $t('user.login.login') }}
                </a-button>
            </a-form-item>

            <div class="user-login-other h-center">
                <router-link class="h-center" :to="{ name: 'register' }">{{ $t('user.login.signup') }}</router-link>
            </div>
        </a-form>
    </div>
</template>

<script>
import { login, formatUserInfo, getUserInfo, getSmsCaptcha } from '../../common/api/setting'

export default {
    components: {},
    data() {
        return {
            customActiveKey: 'account',
            loginBtn: false,
            loginType: 0,
            isLoginError: false,
            form: this.$form.createForm(this),
            username: localStorage.getItem('username') || '',
            password: localStorage.getItem('password') || '',
            mobile: localStorage.getItem('mobile') || '',
            rememberMe: localStorage.getItem('rememberMe') == 'true' || false,
            state: {
                time: 60,
                loginBtn: false,
                loginType: 0,
                smsSendBtn: false,
            },
        }
    },
    created() {},
    methods: {
        // handler
        handleusernameOrEmail(rule, value, callback) {
            const { state } = this
            const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
            if (regex.test(value)) {
                state.loginType = 0
            } else {
                state.loginType = 1
            }
            callback()
        },
        handleTabClick(key) {
            this.customActiveKey = key
            // this.form.resetFields()
        },
        handleSubmit(e) {
            e.preventDefault()
            const {
                form: { validateFields },
                state,
                customActiveKey,
            } = this

            state.loginBtn = true

            const validateFieldsKey =
                customActiveKey === 'account' ? ['username', 'password', 'rememberMe'] : ['mobile', 'captcha']

            validateFields(validateFieldsKey, { force: true }, (err, values) => {
                if (!err) {
                    let loginParams = {}
                    loginParams.one = this.customActiveKey === 'account' ? values.password : values.captcha
                    loginParams.two = this.customActiveKey === 'account' ? values.username : values.mobile
                    loginParams.type = this.customActiveKey
                    if (values.rememberMe) {
                        localStorage.setItem('rememberMe', true)
                        if (this.customActiveKey === 'account') {
                            localStorage.setItem('username', values.username)
                            localStorage.setItem('password', values.password)
                        } else {
                            localStorage.setItem('password', values.mobile)
                        }
                    } else {
                        if (this.customActiveKey === 'account') {
                            localStorage.removeItem('username')
                            localStorage.removeItem('password')
                        } else {
                            localStorage.removeItem('mobile')
                        }
                        localStorage.removeItem('rememberMe')
                    }
                    login(loginParams)
                        .then(res => {
                            if (res.code == 200) {
                                let userInfo = formatUserInfo(res.data)
                                this.userInfo = userInfo
                                if (res.data.roles && res.data.roles.length > 1) {
                                    this.modal.roles = res.data.roles
                                    this.modal.visible = true
                                } else {
                                    this.loginSuccess(userInfo)
                                }
                            } else {
                            }
                        })
                        .catch(err => {
                            console.log(err)
                            this.requestFailed(err)
                        })
                        .finally(() => {
                            state.loginBtn = false
                        })
                } else {
                    setTimeout(() => {
                        state.loginBtn = false
                    }, 600)
                }
            })
        },
        getCaptcha(e) {
            e.preventDefault()
            const {
                form: { validateFields },
                state,
            } = this

            validateFields(['mobile'], { force: true }, (err, values) => {
                if (!err) {
                    state.smsSendBtn = true

                    const interval = window.setInterval(() => {
                        if (state.time-- <= 0) {
                            state.time = 60
                            state.smsSendBtn = false
                            window.clearInterval(interval)
                        }
                    }, 1000)

                    const hide = this.$message.loading('验证码发送中..', 0)
                    getSmsCaptcha({ mobile: values.mobile })
                        .then(res => {
                            setTimeout(hide, 2500)
                            this.$notification['success']({
                                message: '提示',
                                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                                duration: 8,
                            })
                        })
                        .catch(err => {
                            setTimeout(hide, 1)
                            clearInterval(interval)
                            state.time = 60
                            state.smsSendBtn = false
                            this.requestFailed(err)
                        })
                }
            })
        },
        loginSuccess(res) {
            console.log(res)
            const { roles, menus, token } = res
            localStorage.setItem('token', token)
            if (Array.isArray(roles) && roles.length > 1) {
                localStorage.setItem('showRoleModal', '1')
            }
            localStorage.setItem('isLogin', true)
            this.$store.commit('setUserInfo', res)
            if (!menus || !menus.length) {
                this.$message.warning('您无任何权限, 请联系管理员!!')
                this.isLoginError = false
                return
            }
            this.$router.push({
                path: '/',
            })
            // 延迟 1 秒显示欢迎信息
            setTimeout(() => {
                this.$notification.success({
                    message: '欢迎',
                    description: '欢迎回来',
                })
            }, 1000)
            this.isLoginError = false
        },
        requestFailed(err) {
            // this.isLoginError = true
            // this.errorMessage = ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试'
            // this.$notification['error']({
            //     message: '错误',
            //     description: this.errorMessage,
            //     duration: 4,
            // })
        },
    },
}
</script>

<style lang="less" scoped>
.main {
    min-width: 260px;
    width: 368px;
}

h1 {
    text-align: center;
    font-weight: bold;
}

.user-layout-login {
    label {
        font-size: 14px;
    }

    .getCaptcha {
        display: block;
        width: 100%;
        height: 40px;
    }

    .forge-password {
        font-size: 14px;
    }

    button.login-button {
        padding: 0 15px;
        font-size: 16px;
        height: 40px;
        width: 100%;
    }

    .user-login-other {
        text-align: left;
        margin-top: 24px;
        line-height: 22px;

        .item-icon {
            font-size: 24px;
            color: rgba(0, 0, 0, 0.2);
            margin-left: 16px;
            vertical-align: middle;
            cursor: pointer;
            transition: color 0.3s;

            &:hover {
                color: #1890ff;
            }
        }

        .register {
            float: right;
        }
    }
}
</style>
